import { Text, StyleSheet, View, Image, Platform, PermissionsAndroid, TouchableWithoutFeedback, ActivityIndicator, TouchableOpacity } from 'react-native'
import React, { useState, useEffect } from 'react'
import { Provider, Button, InputItem, Toast } from '@ant-design/react-native'
import { useSelector, useDispatch, connect } from 'react-redux'
import LinearGradient from 'react-native-linear-gradient';
import ShadowCard from "../../utils/shadowCard"
import { pTx } from "../../utils/dimensions"
import { SetIsWallet } from "../../redux/features/walletSlice"
import { launchImageLibrary } from 'react-native-image-picker';
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import httpApi from "../../api"


const mapStateToProps = state => state.wallet

const PersonalInfo = (props) => {
    const [name, setName] = useState("")
    const [curFiles, setCurFiles] = useState([])
    const [loading, setLoading] = useState()
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];

    const complete = async () => {
        try {
            setLoading(true)
            if (curFiles[0]?.uri) {
                const image = await httpApi.uploadMinio(curFiles)
                const res = await httpApi.setUserProfilePhoto({ profilePhoto: image.data.FileNames[0] })
                realm.write(() => {
                    userInfo.ProfilePhoto = image?.data?.FileNames[0]
                })
            }
            if (name) {
                await httpApi.setUserNickName({ nickname: name })
                realm.write(() => {
                    userInfo.NickName = name
                })
            }
            props.SetIsWallet(true)
        } catch (error) {
            console.log(error)
        }
        setLoading(false)
    }
    cameraPermission = async () => {
        launchImageLibrary({
            mediaType: 'photo',
            maxWidth: 1000,
            maxHeight: 1000,
            quality: 1,
            videoQuality: 'low',
            includeBase64: true,
            selectionLimit: 1,
        }, res => {
            if (res.didCancel) {
                return false;
            } else {
                const curFiles = res.assets;
                setCurFiles(curFiles)
            }
        })
    }
    const requestCameraPermission = async () => {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                {
                    title: '需要访问相册',
                    message: '需要访问相册',
                    buttonPositive: '',
                },
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            } else {
            }
        } catch (err) {
            console.warn(err)
        }
    }

    useEffect(() => {
        requestCameraPermission()
        return () => {
            requestCameraPermission()
        }
    }, [])

    return (
        <>
            <View style={styles.page}>
                <TouchableWithoutFeedback >
                    <View style={styles.imagePicker}  >
                        {
                            curFiles[0]?.uri ? <Image
                                style={styles.logo}
                                source={{ uri: curFiles[0]?.uri }} />
                                : <Image style={styles.logo} source={require('../../assets/logo.png')}></Image>

                        }
                        {/* <Text style={styles.imagePickerName}>点击选择头像</Text> */}
                    </View>
                </TouchableWithoutFeedback>
                <View>
                    <Text style={styles.label}>输入您的昵称</Text>
                    <View style={styles.InputItem}>
                        <InputItem
                            type={'text'}
                            maxLength={15}
                            value={name}
                            onChange={(value) => setName(value)}
                        >
                        </InputItem>
                    </View>
                </View>
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={[styles.linearGradient]}>
                        <TouchableOpacity type="primary" disabled={loading} style={[styles.button]} onPress={() => complete()}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>下一步</Text>
                            </>

                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
        </>
    )
}

export default connect(mapStateToProps, { SetIsWallet })(PersonalInfo)


const styles = StyleSheet.create({
    page: {
        flex: 1,
        paddingHorizontal: pTx(36),
    },
    logo: {
        marginTop: pTx(30),
        width: pTx(130),
        height: pTx(130),
        alignSelf: "center"
    },
    imagePickerName: {
        marginTop: pTx(12),
        alignSelf: "center",
        fontSize: pTx(12),
    },
    name: {
        alignSelf: "center",
        fontSize: pTx(24),
        color: "rgba(10, 12, 20, 1)"
    },
    label: {
        marginTop: pTx(72),
        fontSize: pTx(12),
        color: "rgba(114, 114, 114, 1)"
    },
    InputItem: {
        marginTop: pTx(16),
        marginLeft: 0,
        paddingLeft: 0,
        height: pTx(47),
        fontSize: pTx(16),
        backgroundColor: "rgba(237, 237, 237, 1)",
        borderWidth: 0,
        borderRadius: 6,
        overflow: "hidden",
        justifyContent: "center"
    },
    footerButton: {
        paddingTop: pTx(15),
        paddingBottom: pTx(25),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 6
    },
    button: {
        width: pTx(303),
        height: pTx(55),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    }
})